package com.yuda.afterexamscore.controller;

import com.yuda.afterexamscore.domain.DpQuesScore;
import com.yuda.afterexamscore.service.IDpQuesScoreService;
import com.yuda.afterexamscore.service.IThQuesScoreMappingService;
import com.yuda.common.core.utils.StringUtils;
import com.yuda.common.core.utils.poi.ExcelUtil;
import com.yuda.common.core.web.controller.BaseController;
import com.yuda.common.core.web.domain.AjaxResult;
import com.yuda.common.core.web.page.TableDataInfo;
import com.yuda.common.log.annotation.Log;
import com.yuda.common.log.enums.BusinessType;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 单题分数（如每科有30道题目的话，那么5万个学生应该有30*5*17=2500万条数据)Controller
 *
 * @author wyn
 * @date 2021-05-11
 */
@RestController
@RequestMapping("/dpQuesScore")
public class DpQuesScoreController extends BaseController
{
    @Autowired
    private IDpQuesScoreService dpQuesScoreService;

    @Autowired
    private IThQuesScoreMappingService thQuesScoreMappingService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询单题分数（如每科有30道题目的话，那么5万个学生应该有30*5*17=2500万条数据)列表
     */
//    @PreAuthorize(hasPermi = "operationcenter:score:list")
    @GetMapping("/list")
    public TableDataInfo list(DpQuesScore dpQuesScore)
    {
        startPage();
        List<DpQuesScore> list = dpQuesScoreService.selectDpQuesScoreList(dpQuesScore);
        return getDataTable(list);
    }

    /**
     * 导出单题分数（如每科有30道题目的话，那么5万个学生应该有30*5*17=2500万条数据)列表
     */
//    @PreAuthorize(hasPermi = "operationcenter:score:export")
    @Log(title = "单题分数（如每科有30道题目的话，那么5万个学生应该有30*5*17=2500万条数据)", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DpQuesScore dpQuesScore) throws IOException
    {
        List<DpQuesScore> list = dpQuesScoreService.selectDpQuesScoreList(dpQuesScore);
        ExcelUtil<DpQuesScore> util = new ExcelUtil<DpQuesScore>(DpQuesScore.class);
        util.exportExcel(response, list, "score");
    }

    /**
     * 获取单题分数（如每科有30道题目的话，那么5万个学生应该有30*5*17=2500万条数据)详细信息
     */
//    @PreAuthorize(hasPermi = "operationcenter:score:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(dpQuesScoreService.selectDpQuesScoreById(id));
    }

    /**
     * 新增单题分数（如每科有30道题目的话，那么5万个学生应该有30*5*17=2500万条数据)
     */
//    @PreAuthorize(hasPermi = "operationcenter:score:add")
    @Log(title = "单题分数（如每科有30道题目的话，那么5万个学生应该有30*5*17=2500万条数据)", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DpQuesScore dpQuesScore)
    {
        return toAjax(dpQuesScoreService.insertDpQuesScore(dpQuesScore));
    }

    /**
     * 修改单题分数（如每科有30道题目的话，那么5万个学生应该有30*5*17=2500万条数据)
     */
//    @PreAuthorize(hasPermi = "operationcenter:score:edit")
    @Log(title = "单题分数（如每科有30道题目的话，那么5万个学生应该有30*5*17=2500万条数据)", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DpQuesScore dpQuesScore)
    {
        return toAjax(dpQuesScoreService.updateDpQuesScore(dpQuesScore));
    }

    /**
     * 删除单题分数（如每科有30道题目的话，那么5万个学生应该有30*5*17=2500万条数据)
     */
//    @PreAuthorize(hasPermi = "operationcenter:score:remove")
    @Log(title = "单题分数（如每科有30道题目的话，那么5万个学生应该有30*5*17=2500万条数据)", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(dpQuesScoreService.deleteDpQuesScoreByIds(ids));
    }

    /**
     * 从formal_answer里把数据插入到dp_ques_score
     */
//    @PreAuthorize(hasPermi = "operationcenter:score:remove")
//    @Log(title = "单题分数（如每科有30道题目的话，那么5万个学生应该有30*5*17=2500万条数据)", businessType = BusinessType.DELETE)
    @ApiOperation("从formal_answer里把数据插入到dp_ques_score,每次执行会把dp_ques_score数据清空,慎用!!!!!!!!!!!!!!!!!!!!!!!!!!,pg_type>=65的gaige=0其他的gaige=1")
    @Log(title = "insertFromFormalAnswer", businessType = BusinessType.INSERT)
    @PostMapping("/insertFromFormalAnswer")
    public AjaxResult insertFromFormalAnswer() throws InterruptedException {
        //计算时间:初始时间
        Instant insOne = Instant.now();
        //先清空dp_ques_score表
        dpQuesScoreService.truncateTable();
        //分科目插入---------------------------------不操作特殊的题目,比如四选二--------------------------------------------
        List<String> spartaSubjects = thQuesScoreMappingService.queryAllSubjectId();
        int threadNum = spartaSubjects.size();
        CountDownLatch countDownLatch = new CountDownLatch(threadNum);
        ExecutorService executor = Executors.newFixedThreadPool(20);
        if (threadNum>0){
            for (String spartaSubject : spartaSubjects) {
                Runnable task = new DpQuesScoreController.MultithreadingOfInsertFromFormalAnswer(countDownLatch,spartaSubject);
                // 执行
                executor.execute(task);
            }
        }
        countDownLatch.await();
        executor.shutdown();//关闭线程池
        //计算时间:结束时间
        Instant insTwo = Instant.now();
        //插入完成后将dp_subject_score的个数存入redis里,好让dp_subject_score查询快一点
        String count = dpQuesScoreService.querySubjectCount();
        if (StringUtils.isNotEmpty(count)){
            redisTemplate.opsForValue().set("dpsubjectcount",count,30l, TimeUnit.MINUTES);
        }
        return AjaxResult.success("Difference in seconds(秒) : " + Duration.between(insOne, insTwo).getSeconds());
    }

    /**
     * 从formal_answer里把数据插入到dp_ques_score,特殊题型,选择题四选二,type=6 会把type = 6的全部删除
     *
     */
    @ApiOperation("从formal_answer里把数据插入到dp_ques_score,特殊题型,选择题四选二(误用!!!!!还没开发!!!!!)")
    @PostMapping("/insertFromFormalAnswerOfSiXuanEr")
    public AjaxResult insertFromFormalAnswerOfSiXuanEr() throws InterruptedException {
        //计算时间:初始时间
        Instant insOne = Instant.now();
        //插入四选二

        //计算时间:结束时间
        Instant insTwo = Instant.now();
        return AjaxResult.success("Difference in seconds(秒) : " + Duration.between(insOne, insTwo).getSeconds());
    }

    /**
     * 返回插入进度
     *
     */
    @GetMapping("/insertQuesScoreProcess")
    @ApiOperation("返回插入进度")
    public AjaxResult insertQuesScoreProcess() throws InterruptedException {
        return AjaxResult.success(dpQuesScoreService.insertQuesScoreProcess());
    }

    //---------------------------------------------------分割线--------------------------------------------------------------------------------------------------

    /**
     * 多线程之插入dp_ques_score
     *
     */
    private class MultithreadingOfInsertFromFormalAnswer implements Runnable {
        private CountDownLatch threadsSignal;
        private String subjectId;
        public MultithreadingOfInsertFromFormalAnswer(CountDownLatch threadsSignal,String subjectId) {
            this.threadsSignal = threadsSignal;
            this.subjectId = subjectId;
        }

        @Override
        public void run() {
            int i = dpQuesScoreService.insertFromFormalAnswer(subjectId);
            // 线程结束时计数器减1
            threadsSignal.countDown();//必须等核心处理逻辑处理完成后才可以减1
        }
    }
}
